package top.fwpsl.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
import top.fwpsl.config.RedisClusterConfig;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @auther: 风戏fw
 * @date: 2020/11/25
 */
//@Configuration
//@WebListener
public class MyListener implements ServletContextListener {

    @Autowired
    private MySubscribe mySubscribe;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(RedisClusterConfig.maxIdle);
        poolConfig.setMinIdle(RedisClusterConfig.minIdle);
        poolConfig.setMaxTotal(RedisClusterConfig.maxTotal);
        poolConfig.setMaxWaitMillis(RedisClusterConfig.maxWaitMillis);
        //redis连接归还时检测可用服务的数量是否发生变化，如果发生变化就需要销毁这个连接
        poolConfig.setTestOnReturn(true);
        //redis连接 借出 时检测可用
        poolConfig.setTestOnBorrow(true);
        //连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
        poolConfig.setBlockWhenExhausted(false);

        Set<HostAndPort> jedisClusterNodes;
        //Jedis Cluster will attempt to discover cluster nodes automatically
        if (RedisClusterConfig.serverHosts != null) {
            jedisClusterNodes = RedisClusterConfig.serverHosts.stream().map(node -> {
                String[] splits = node.split(":");
                return new HostAndPort(splits[0], Integer.parseInt(splits[1]));
            }).collect(Collectors.toSet());
        } else {
            jedisClusterNodes = new HashSet<>();
        }

        JedisCluster jedisCluster = new JedisCluster(jedisClusterNodes, RedisClusterConfig.connectionTimeout,
                RedisClusterConfig.soTimeout, RedisClusterConfig.maxAttempts, poolConfig);

        new Thread(() -> jedisCluster.subscribe(mySubscribe, "fw")).start();
    }


    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("ServletContext容器销毁了。。。");
    }
}
